import * as md5 from 'md5';
import { login } from '../api/login';
import * as configuration from '../configuration';
import { InputBox } from '../helper/InputBox';
import { log } from '../helper/outputChannel';
import { Memory } from '../memory';
import { Aborter } from '../network/aborter';
import { fetchApiListByUser } from './fetchApiList';

const aborter = new Aborter();

export async function addUser() {
  log.show(true);
  
  const user = { ...Memory.userTemplate };
  try {
    let input = InputBox.create();
    input.title = '添加torna用户 - 输入torna地址';
    input.placeholder = '输入torna地址';
    input.value = '';
    input.totalSteps = 3;
    input.step = 1;
    input.ignoreFocusOut = true;

    input = await input.show();
    user.url = input.value.trim().replace(/\/$/, '');
    input.title = '添加torna用户 - 输入torna用户名';
    input.placeholder = '输入torna用户名';
    input.value = '';
    input.step = 2;

    input = await input.show();
    user.username = input.value.trim();
    input.title = '添加torna用户 - 输入torna密码';
    input.placeholder = '输入torna密码';
    input.value = '';
    input.step = 3;

    input = await input.show();
    user.password = md5(input.value.trim()).toLowerCase();
    input.value = '';
    input.hide();

    log.info(`[TAV] 登陆中...${user.username} ${user.url}`);

    const { token } = await login(user.url + '/system/login', {
      username: user.username,
      password: user.password,
    }, aborter.single());
    user.token = 'Bearer ' + token;
    configuration.addUser(user);

    log.info(`[TAV] 登陆成功 ${user.username} ${user.url}`);

    await fetchApiListByUser(user);

  } catch (error: any) {
    error && log.error(error);
  } finally {
    aborter.clear();
  }
}

